<?php
//消费券服务

namespace App\Services;

use App\Repositories\CouponReceiveRepository;
use Carbon\Carbon;

class CouponService
{

    /**
     * 获取列表
     * @param $query
     * @param $offset
     * @param $limit
     * @param $orderType
     * @return array|mixed
     */
    public static function getList($query = [], $offset = 0, $limit = 20, $orderType = 0)
    {
        //获取证书关联信息
        $repo = new CouponReceiveRepository();
        $repo->buildQuery($query);
        $list = $repo
            ->getList($offset, $limit, $orderType)
            ->toarray();

        return self::getListFormat($list);
    }

    /**
     * 获取单条
     * @param $query
     * @return arra
     */
    public static function getRow($query = [])
    {
        //获取证书关联信息
        $repo = new CouponReceiveRepository();
        $repo->buildQuery($query);
        $row = $repo
            ->getRow();
        if (!$row) {
            return [];
        }
        $row = $row->toArray();
        $list = self::getListFormat([$row]);

        return reset($list);
    }

    /**
     * 获取总数
     * @param $query
     * @return arra
     */
    public static function getTotal($query = [])
    {
        //获取证书关联信息
        $repo = new CouponReceiveRepository();
        $repo->buildQuery($query);

        return $repo->getTotal();
    }

    /**
     * 获取页面结构列表
     * @param $query
     * @param $page
     * @param $pageSize
     * @param $orderType
     * @return int[]
     */
    public static function getPageList($query = [], $page = 1, $pageSize = 20, $orderType = 0)
    {
        $output = [
            'total'     => 0,
            'totalPage' => 0,
            'pageSize'  => (int) $pageSize,
            'list'      => [],
        ];
        //获取证书关联信息
        $repo = new CouponReceiveRepository();
        $repo->buildQuery($query);
        $total = $repo->getTotal();
        if (!$total) {
            return $output;
        }
        $offset = ($page - 1) * $pageSize;
        $output['total'] = $total;
        $output['totalPage'] = (int) ceil($total / $pageSize);
        $list = $repo
            ->getList($offset, $pageSize, $orderType)
            ->toarray();
        //格式化列表信息
        $output['list'] = self::getListFormat($list);

        return $output;
    }

    public static $receiveStatusList = [
        1 => '未领取',
        2 => '已领取',
    ]; //领取状态

    public static $consumeStatusList = [
        1 => '未核销',
        2 => '已核销',
    ]; //核销状态

    /**
     * 页面列表信息格式化
     * @param $list
     * @return array|mixed
     */
    public static function getListFormat($list = [])
    {
        if (!$list) {
            return [];
        }
        foreach ($list as &$val) {
            //核销状态
            if(!empty($val['consume_status'])) {
                $val['consume_status_text'] = self::$consumeStatusList[$val['consume_status']] ?? '';
            }
            //券金额
            if(!empty($val['coupon_amount_format'])) {
                $val['coupon_amount_format'] = $val['coupon_amount'] / 100;
            }
            //券限额
            if(!empty($val['coupon_quota'])) {
                $val['coupon_quota_format'] = $val['coupon_quota'] / 100;
            }
        }
        unset($val);

        return $list;
    }

    /**
     * 保存
     * @param $query
     * @return array
     */
    public static function save($data = [])
    {
        if (empty($data['coupon_id']) || empty($data['receiver_id']) || empty($data['activity_id'] || empty($data['stock_id']))
            || empty($data['coupon_amount']) || empty($data['out_request_no'])) {
            return resultError('参数缺失');
        }
        $repo = new CouponReceiveRepository();
        $res = $repo->save([
            'activity_id'       => $data['activity_id'], //活动id
            'coupon_id'         => $data['coupon_id'], //券id，由微信返回
            'receiver_id'       => $data['receiver_id'], //领券人id
            'openid'            => $data['openid'], //领券人id
            'stock_id'          => $data['stock_id'], //批次id
            'coupon_name'       => $data['coupon_name'], //券名称
            'receive_date'      => $data['receive_date'], //领取时间
            'coupon_amount'     => $data['coupon_amount'], //券金额，单位：分
            'coupon_quota'      => $data['coupon_quota'], //券限额，单位：分
            'coupon_desc'       => $data['coupon_desc'], //券描述
            'coupon_start_date' => $data['coupon_start_date'], //使用时间-开始
            'coupon_end_date'   => $data['coupon_end_date'], //使用时间-结束
            'out_request_no'    => $data['out_request_no'], //本次发放 商户单据号，需保证唯一
        ]);
        if (!$res) {
            return resultError('保存失败');
        }

        return resultSuccess([
            'id' => $res,
        ], '保存成功');
    }

    /**
     * 更新核销状态
     * @param $id
     * @param $receiveStatus
     * @return array
     */
    public static function updateConsumeStatus($id, $consumeStatus)
    {
        if (empty(self::$consumeStatusList[$consumeStatus])) {
            return resultError('参数有误');
        }
        $data = [
            'consume_status' => $consumeStatus,
        ];
        if ($consumeStatus == 2) {
            //核销时更新核销时间
            $data['consume_date'] = Carbon::now()->toDateTimeString();
        }
        $res = (new CouponReceiveRepository)->updateFields($id, $data);
        if (!$res) {
            return resultError('更新失败');
        }

        return resultSuccess([], '更新成功');
    }


    /**
     * 根据微信券id更新券核销状态
     * @param $couponId
     * @param $consumeStatus
     * @return array
     */
    public static function updateConsumeStatusByCouponId($couponId, $consumeStatus)
    {
        $couponInfo = self::getRow([
            'coupon_id' => $couponId,
        ]);
        if (!$couponInfo) {
            return resultError('券id有误');
        }

        $res = self::updateConsumeStatus($couponInfo['id'], $consumeStatus);
        if ($res['errcode']) {
            return $res;
        }

        return $res;
    }


}
